#include "writeNormals.hpp"
#include "MQ3DLib.hpp"
#include "Log.hpp"
#include <algorithm>
#include <vector>
#include <cassert>
using namespace std;
using namespace m3g;

/**
 * 
 */
unsigned int writeNormals (M3GWriter* writer, MQObject mq_obj, const vector<MQPoint>& normals, float* scale_, float* bias_)
{
	unsigned int object_index;

	int vertex_count = mq_obj->GetVertexCount ();
	int face_count   = mq_obj->GetFaceCount ();

    assert (vertex_count == normals.size());


	float scale   = 255/2.f;
	float bias[3] = {-1/2.f, -1/2.f, -1/2.f};

    int component_size  = 1;
    int component_count = 3;
	
	M3GObject3DStruct    obj;
	M3GVertexArrayStruct varry;
	varry.component_size  = component_size;
	varry.component_count = component_count;
	varry.encoding        = M3GVertexArrayStruct::ENCODING_0;
	varry.vertex_count    = vertex_count;
	varry.char_components = new char*[vertex_count];
	for (int v = 0; v < vertex_count; v++) {
		varry.char_components[v]    = new char[3];
		varry.char_components[v][0] = (char)(normals[v].x * scale + bias[0] + 0.5f);
		varry.char_components[v][1] = (char)(normals[v].y * scale + bias[1] + 0.5f);
		varry.char_components[v][2] = (char)(normals[v].z * scale + bias[2] + 0.5f);
	}


	writer->startObject       (M3G_TYPE_VERTEX_ARRAY, &object_index);
	writer->writeObject3D     (obj);
	writer->writeVertexArray  (varry);
	writer->endObject         ();

	*scale_  = 1/scale;
	bias_[0] = -bias[0]/scale;
	bias_[1] = -bias[1]/scale;
	bias_[2] = -bias[2]/scale;

   	Log:: print (" [%d] Write VertexArray(normals) :", object_index);
    Log:: print ("  vertex_count=%d"      , vertex_count   );
    Log:: print (", component_count=%d"  , component_count);
    Log:: print (", component_size=%d.\n", component_size );

    return object_index;
}